"""
生成文档目录:

- [分享消息相关接口](/api/app_server/share_msg/index.md)
  - [分享消息设为已读](/api/app_server/share_msg/read_share_msg.md)
  - [删除分享消息](/api/app_server/share_msg/delete_share_msg.md)

1、按目录结构遍历；
2、当前为目录时，使用目录下的index.md中标题做为目录标题

"""

import os

# 根目录
root_dir = ""

# 遍历目录,组装 tree 目录并按字典序排序
def walkFile(nodeList, dir, depth):
    for fileName in os.listdir(dir):
        source = os.path.join(dir, fileName)
        if os.path.isdir(source): 
            dirTitle = readDirIndex(source)
            node = {
                "title": dirTitle,
                "path": os.path.join(source, "index.md"), # 目录下的 index.md 做为该目录首页
                "depth": depth,
                "children": []
            }
            nodeList.append(node)
            walkFile(node["children"], source, depth = depth + 1)
        elif fileName != "index.md":
            title = readTitle(source)
            if title:
                nodeList.append({
                    "title": title,
                    "path": source,
                    "depth": depth
                })
            pass
    nodeList.sort(key=lambda n: n['title'])

# 读取一级标题
def readTitle(path):
    with open(path, 'r', encoding='utf-8') as f:
        for line in f.readlines():
            if line.startswith("# "):
                return line.strip("\n").split(" ", 1)[1]

# 读取目录index.md文件
def readDirIndex(path): 
    path = os.path.join(path, "index.md")
    if os.path.exists(path):
        with open(path, 'r', encoding='utf-8') as f:
            for line in f.readlines():
                if line.startswith("# "):
                    return line.strip("\n").split(" ", 1)[1]
    else:
        return ""

# tree 转 list
def convertList(nodeTree, nodes):
    for node in nodeTree:
        nodes.append(formatTitle(node["title"], node["path"], node["depth"]))
        if "children" in node:
            convertList(node["children"], nodes)
    
# 写入文件
def writeSidebar(dir, nodeList):
    with open(dir, 'w', encoding="utf-8") as f:
        f.writelines('\n'.join(nodeList))

# 格式化标题
def formatTitle(title, path, depth):
    relative_path = path.replace(root_dir, "/api").replace("\\", "/")
    return "  " * depth + "- [%s](%s)" % (title, relative_path)

def main():

    global root_dir
    root_dir = "/mnt/d/work/design/open_api"

    api_dir = "app_server"

    nodeTree = []
    walkFile(nodeTree, os.path.join(root_dir, api_dir), 0)
    # print(json.dumps(node))
    nodes = []
    convertList(nodeTree, nodes)
    # writeSidebar(os.path.join(root_dir, api_dir, "_sidebar.md"), nodes)
    writeSidebar("out/_sidebar.md", nodes)

if __name__ == "__main__": 
    main()